import React, { useEffect, useState, useMemo, useCallback } from 'react';
import {
  Form,
  Input,
  Drawer,
  Message,
  Button,
  Checkbox,
  InputNumber,
  Tag,
} from '@arco-design/web-react';
import { issuedTelepathyLimit } from '@/api/wallet';
import styles from '@/pages/telepathy/educationTelepathy/style/index.module.less';
import { getUserByKeyword } from '@/api/userData';
import { validatePositiveInteger } from '@/utils/formValidate';

const FormItem = Form.Item;
const InputSearch = Input.Search;
const CheckboxGroup = Checkbox.Group;

interface Props {
  visible: boolean;
  modalTitle: string;
  changeVisible: (visible: boolean) => void;
}

function FormModal(props: Props) {
  const { visible, changeVisible, modalTitle } = props;
  const [form] = Form.useForm();

  // 搜索时禁用搜索输入
  const [isDisabled, setIsDisabled] = useState(false);
  const [searchResult, setSearchResult] = useState([]);
  const [currentUserList, setCurrentUserList] = useState([]);
  const [choosedUserList, setChosenUserList] = useState([]);

  useEffect(() => {
    if (!visible) return;
    form.resetFields();
    setSearchResult([]);
    setCurrentUserList([]);
    setChosenUserList([]);
  }, [visible]);

  const onOk = () => {
    form.validate().then(async (value) => {
      if (currentUserIds.length === 0) {
        Message.warning('请添加需要下发的用户');
        return;
      }
      const telepathyValue = form.getFieldValue('telepathyValue');

      const TelepathyIssuedLimitList = currentUserIds.map((item) => {
        return {
          CTLUserId: item,
          TelepathyIssuedLimit: telepathyValue,
        };
      });
      const reqData = {
        TelepathyLimitIssuedParams: {
          PayPassword: '', //支付密码
          ConfirmIssued: true, // 是否下发
          TelepathyIssuedLimitList: TelepathyIssuedLimitList,
        },
      };
      const res: any = await issuedTelepathyLimit(reqData);

      if (res.StatusCode === 200) {
        Message.success(res.Message);
        changeVisible(false);
      } else {
        Message.error(res.Message);
      }
    });
  };

  const onCancel = () => {
    form.resetFields();
    changeVisible(false);
  };

  const currentUserIds = useMemo(() => {
    return currentUserList.map((item) => {
      return item.CTLUserId;
    });
  }, [currentUserList]);
  // 搜索用户
  const handleSearchUser = useCallback(
    async (val: string) => {
      if (!val) {
        Message.warning('请输入搜索关键词');
      } else {
        setIsDisabled(true);
        const res: any = await getUserByKeyword({
          KeyWord: val,
        });
        setIsDisabled(false);
        if (res.StatusCode === 200) {
          setSearchResult(res.Result.Datas);
          setIndeterminate(false);
          setCheckAll(true);
          setChosenUserList(res.Result.Datas);
        } else {
          Message.error(res.Message);
        }
      }
    },
    [searchResult]
  );

  const addChooseUser = () => {
    if (!choosedUserList.length) {
      Message.warning('请选择用户');
      return;
    }
    const newAddItem = [];
    for (let index = 0; index < choosedUserList.length; index++) {
      const element = choosedUserList[index];
      if (!currentUserIds.includes(element.CTLUserId)) {
        newAddItem.push(element);
      }
    }
    setCurrentUserList([...currentUserList, ...newAddItem]);
  };

  const onChangeCheck = (list) => {
    setChosenUserList(list);
  };
  useEffect(() => {
    if (choosedUserList.length === 0 && searchResult.length === 0) return;
    setIndeterminate(
      !!(
        choosedUserList.length && choosedUserList.length !== searchResult.length
      )
    );
    setCheckAll(!!(choosedUserList.length === searchResult.length));
  }, [choosedUserList]);

  const onCloseTag = (ID: string) => {
    const newItems = currentUserList.filter((i) => i.CTLUserId !== ID);
    setCurrentUserList(newItems);
  };

  const [indeterminate, setIndeterminate] = useState(true);
  const [checkAll, setCheckAll] = useState(false);
  const onChangeAll = (checked: boolean) => {
    if (checked) {
      setIndeterminate(false);
      setCheckAll(true);
      setChosenUserList(searchResult);
    } else {
      setIndeterminate(false);
      setCheckAll(false);
      setChosenUserList([]);
    }
  };

  return (
    <>
      <Drawer
        title={modalTitle}
        visible={visible}
        onOk={onOk}
        onCancel={onCancel}
        autoFocus={false}
        focusLock={false}
        okText="下发"
        style={{ width: '700px' }}
      >
        <Form
          form={form}
          layout="vertical"
          labelCol={{ style: { flexBasis: 100 } }}
          wrapperCol={{ style: { flexBasis: 'calc(100% - 100px)' } }}
        >
          <FormItem label="搜索用户" field="keyWord">
            <InputSearch
              autoComplete={'off'}
              disabled={isDisabled}
              searchButton
              allowClear
              placeholder="请输入账号"
              onSearch={(value) => handleSearchUser(value)}
              style={{ minWidth: 250 }}
            />
          </FormItem>
          <FormItem label="用户匹配结果" field="searchResultUser">
            <div className={styles['user-label-box']}>
              {searchResult.length > 0 && (
                <>
                  <Button type="outline" onClick={addChooseUser}>
                    添加
                  </Button>
                  <div>
                    <div style={{ marginTop: 20 }}>
                      <Checkbox
                        onChange={onChangeAll}
                        checked={checkAll}
                        indeterminate={indeterminate}
                      >
                        全选
                      </Checkbox>
                    </div>
                    <CheckboxGroup
                      direction="vertical"
                      onChange={onChangeCheck}
                      value={choosedUserList}
                    >
                      {searchResult.map((item) => (
                        <Checkbox key={item.CTLUserId} value={item}>
                          {`${item.CTLAccount} - ${item.CTLUserName}`}
                        </Checkbox>
                      ))}
                    </CheckboxGroup>
                  </div>
                </>
              )}
            </div>
          </FormItem>
          <FormItem label="当前用户">
            <div className={styles['user-label-box']}>
              {currentUserList.length > 0 &&
                currentUserList.map((item, index) => (
                  <Tag
                    key={item.CTLUserId}
                    closable
                    onClose={() => {
                      onCloseTag(item.CTLUserId);
                    }}
                    style={{ margin: '0 8px 8px 0' }}
                  >
                    {item.CTLUserName}
                  </Tag>
                ))}
            </div>
          </FormItem>
          <FormItem
            field="telepathyValue"
            label="单个用户获得算力值"
            rules={[{ required: true, validator: validatePositiveInteger }]}
          >
            <InputNumber
              min={0}
              placeholder="请输入"
              style={{ width: '100%' }}
              autoComplete="off"
            />
          </FormItem>
        </Form>
      </Drawer>
    </>
  );
}

export default FormModal;
